<!DOCTYPE html>
<html>
<head>
  <title>提示词2</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" crossorigin="" href="/main.css">
</head>
<body>
<div class="container mt-5">
  <h2>AI Chat 提示词2</h2>

  <!-- Chat Section -->
  <div class="card mb-4">
    <div class="card-header">
      流式聊天
    </div>
    <div class="card-body">
      <div class="chat-container" id="chatContainer"></div>
      <div class="input-group">
        <input type="text" class="form-control" id="messageInput" placeholder="请输入成语...">
        <button class="btn btn-primary" onclick="sendMessage()">发送</button>
      </div>
    </div>
  </div>
</div>

<script>
  function appendMessage(message, isUser) {
    const chatContainer = document.getElementById('chatContainer');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
    messageDiv.innerHTML = message;
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }

  async function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    if (!message) {
      return;
    }

    // 添加对话框【用户】
    const chatContainer = document.getElementById('chatContainer');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message user-message`;
    messageDiv.innerHTML = message;
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;

    messageInput.value = '';

    try {
      // 创建 EventSource 实例，连接到后端的 SSE 接口
      const eventSource = new EventSource('/prompt/chat2?idiom=' + encodeURIComponent(message));

      // 添加对话框【AI】
      const aiMessageDiv = document.createElement('div');
      aiMessageDiv.className = `message ai-message`;
      chatContainer.appendChild(aiMessageDiv);
      chatContainer.scrollTop = chatContainer.scrollHeight;

      let think = false;

      // 监听 message 事件，当接收到服务器发送的消息时触发
      eventSource.onmessage = (event) => {
        let msg = event.data.trim();
        if (msg == "<think>") {
          think = true;
          msg = "";
        } else if (msg == "</think>") {
          think = false;
          msg = "<br/>";
        }

        const thinkSpan = document.createElement('span');
        if (think) {
          thinkSpan.className = `ai-think`;
        }
        thinkSpan.innerHTML = msg;
        aiMessageDiv.appendChild(thinkSpan);
        // aiMessageDiv.innerHTML += msg;
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }

      // 监听 error 事件，当连接出现错误时触发
      eventSource.onerror = (error) => {
        if (error.eventPhase === EventSource.CLOSED) {
          console.log('Connection was closed');
        } else {
          console.error('EventSource failed:', error);
          aiMessageDiv.innerHTML += "发生错误，请稍后重试。";
        }
        // 关闭连接
        eventSource.close();
      };
    } catch (error) {
      console.error('Error:', error);
      appendMessage('发生错误，请稍后重试。', false);
    }
  }

  // 支持按回车发送消息
  document.getElementById('messageInput').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      sendMessage();
    }
  });
</script>
</body>
</html>